<?php
require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $security_question = $_POST['security_question'];
    $security_answer = trim($_POST['security_answer']);

    // 处理自定义安全问题
    if ($security_question === '自定义问题') {
        $security_question = trim($_POST['custom_question']);
    }

    $errors = [];

    // 基础验证
    if (empty($username)) $errors[] = '用户名不能为空';
    if (empty($email)) $errors[] = '邮箱不能为空';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = '邮箱格式无效';
    if (strlen($password) < 8) $errors[] = '密码至少需要8个字符';
    if ($password !== $confirm_password) $errors[] = '两次输入的密码不一致';
    if (empty($security_question)) $errors[] = '请选择安全问题';
    if (strlen($security_answer) < 2) $errors[] = '安全问题答案不能少于2个字符';

    // 检查用户名和邮箱唯一性
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$username, $email]);
    // if ($stmt->rowCount() > 0) $errors[] = '用户名或邮箱已被注册';

    // 处理安全答案哈希
    $answer_hash = password_hash(
        mb_strtolower(trim($security_answer), 'UTF-8'), 
        PASSWORD_DEFAULT
    );

    if (empty($errors)) {
        try {
            // 插入用户数据
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            $stmt = $pdo->prepare("INSERT INTO users 
                (username, email, password, security_question, security_answer_hash)
                VALUES (?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $username,
                $email,
                $hashed_password,
                $security_question,
                $answer_hash
            ]);

            $_SESSION['success'] = '注册成功！请登录';
            header('Location: login.php');
            exit;
        } catch (PDOException $e) {
            $errors[] = '注册失败：' . $e->getMessage();
        }
    }

    // 保留已填写的值
    $_SESSION['form_data'] = [
        'username' => $username,
        'email' => $email,
        'security_question' => $_POST['security_question'],
        'custom_question' => $_POST['custom_question'] ?? ''
    ];
    $_SESSION['errors'] = $errors;
    header('Location: register.php');
    exit;
}

// 获取已保存的表单数据
$form_data = $_SESSION['form_data'] ?? [];
unset($_SESSION['form_data']);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <?php include 'includes/header.php'; ?>
    <title>用户注册</title>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-body">
                        <h2 class="card-title text-center mb-4">用户注册</h2>
                        
                        <!-- <?php include 'includes/alerts.php'; ?> -->

                        <form method="post" novalidate>
                            <!-- 用户名 -->
                            <div class="mb-3">
                                <label class="form-label">用户名</label>
                                <input type="text" 
                                    class="form-control" 
                                    name="username" 
                                    value="<?= htmlspecialchars($form_data['username'] ?? '') ?>" 
                                    required>
                            </div>

                            <!-- 邮箱 -->
                            <div class="mb-3">
                                <label class="form-label">电子邮箱</label>
                                <input type="email" 
                                    class="form-control" 
                                    name="email" 
                                    value="<?= htmlspecialchars($form_data['email'] ?? '') ?>" 
                                    required>
                            </div>

                            <!-- 密码 -->
                            <div class="mb-3 position-relative">
                                <label class="form-label">密码</label>
                                <div class="input-group">
                                    <input type="password" 
                                        class="form-control password-strength" 
                                        name="password" 
                                        id="registerPassword"
                                        placeholder="请输入密码" 
                                        required
                                        data-bs-toggle="popover"
                                        data-bs-custom-class="password-popover custom-popover"
                                        data-bs-placement="auto"
                                        data-bs-trigger="focus"
                                        data-bs-html="true"
                                        data-bs-title="密码要求"
                                        data-bs-content="<ul class='list-unstyled mb-0'>
                                            <li id='popover-length-register' class='text-danger'><i class='bi bi-x-circle-fill'></i> 至少8个字符</li>
                                            <li id='popover-lowercase-register' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含小写字母</li>
                                            <li id='popover-uppercase-register' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含大写字母</li>
                                            <li id='popover-number-register' class='text-danger'><i class='bi bi-x-circle-fill'></i> 包含数字</li>
                                        </ul>">
                                    <button type="button" 
                                            class="btn btn-outline-secondary toggle-password" >
                                        <i class="bi bi-eye"></i> 
                                    </button>
                                </div>
                            </div>

                            <!-- 确认密码 -->
                            <div class="mb-3 position-relative">
                                <label class="form-label">确认密码</label>
                                <div class="input-group">
                                    <input type="password" 
                                        class="form-control"
                                        id="passwordInput"
                                        name="confirm_password" 
                                        placeholder="请确认密码"
                                        required
                                        minlength="8">
                                    <button type="button" 
                                            class="btn btn-outline-secondary toggle-password">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>

                            <!-- 安全问题 -->
                            <div class="mb-3">
                                <label class="form-label">密保问题</label>
                                <select class="form-select" 
                                    name="security_question" 
                                    id="security_question" 
                                    required>
                                    <option value="">请选择安全问题</option>
                                    <option value="您母亲的名字是什么？" 
                                        <?= ($form_data['security_question'] ?? '') === '您母亲的名字是什么？' ? 'selected' : '' ?>>
                                        您母亲的名字是什么？
                                    </option>
                                    <option value="您的出生城市是哪里？"
                                        <?= ($form_data['security_question'] ?? '') === '您的出生城市是哪里？' ? 'selected' : '' ?>>
                                        您的出生城市是哪里？
                                    </option>
                                    <option value="自定义问题"
                                        <?= ($form_data['security_question'] ?? '') === '自定义问题' ? 'selected' : '' ?>>
                                        自定义问题
                                    </option>
                                </select>
                            </div>

                            <!-- 自定义问题（默认隐藏） -->
                            <div class="mb-3" id="custom-question-container" 
                                style="display: <?= ($form_data['security_question'] ?? '') === '自定义问题' ? 'block' : 'none' ?>;">
                                <input type="text" 
                                    class="form-control" 
                                    name="custom_question" 
                                    placeholder="请输入您的自定义安全问题"
                                    value="<?= htmlspecialchars($form_data['custom_question'] ?? '') ?>">
                            </div>

                            <!-- 安全答案 -->
                            <div class="mb-3">
                                <label class="form-label">安全问题答案</label>
                                <input type="text" 
                                    class="form-control" 
                                    name="security_answer" 
                                    required
                                    minlength="2">
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary">立即注册</button>
                                <a href="login.php" class="btn btn-link">已有账号？立即登录</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>


        <script>
        // 仅用于register.php的密码强度验证
        document.addEventListener('DOMContentLoaded', function() {
            const passwordInput = document.getElementById('registerPassword');
            if (passwordInput) {
                const popover = new bootstrap.Popover(passwordInput, {
                    container: 'body',
                    customClass: 'password-popover custom-popover',
                    sanitize: false
                });
                
                function updatePasswordRequirements(value) {
                    const requirements = {
                        length: value.length >= 8,
                        lowercase: /[a-z]/.test(value),
                        uppercase: /[A-Z]/.test(value),
                        number: /\d/.test(value)
                    };

                    Object.keys(requirements).forEach(key => {
                        const element = document.getElementById('popover-'+key+'-register');
                        if (element) {
                            const isValid = requirements[key];
                            element.classList.toggle('text-success', isValid);
                            element.classList.toggle('text-danger', !isValid);
                            const icon = element.querySelector('i');
                            if (icon) {
                                icon.className = isValid ? 'bi bi-check-circle-fill' : 'bi bi-x-circle-fill';
                            }
                        }
                    });
                }
                
                passwordInput.addEventListener('shown.bs.popover', function() {
                    updatePasswordRequirements(this.value);
                });
                
                passwordInput.addEventListener('input', function(e) {
                    updatePasswordRequirements(e.target.value);
                });
            }
        });
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>